package main

import (
	"bytes"
	"github.com/streadway/amqp"
	"log"
	"time"
)

func demo1() {
	connection, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
	if err != nil {
	}
	defer connection.Close()

	//channel
	channel, err := connection.Channel()
	if err != nil {
	}
	defer channel.Close()

	//QueueDeclare
	queue, err := channel.QueueDeclare(
		"hello", // name
		true,    // 声明为持久队列 这样 rabbitmq服务器g掉了也没事，这里注意必须是第一次定义，如果你本身存在，你在重新定义无效
		false,   // delete when unused
		false,   // exclusive
		false,   // no-wait
		nil,     // arguments
	)
	if err != nil {
	}
	//consume
	msgs, err := channel.Consume(
		queue.Name, // queue
		"",         // consumer
		false,      // 注意这里传false,关闭自动消息确认
		false,      // exclusive
		false,      // no-local
		false,      // no-wait
		nil,        // args
	)
	channel.Qos(1, 0, false)
	forver := make(chan bool)
	go func() {
		for d := range msgs {
			log.Printf("Received a message: %s", d.Body)
			dot_count := bytes.Count(d.Body, []byte(".")) // 数一下有几个.
			t := time.Duration(dot_count)
			log.Printf("task is processing....")
			time.Sleep(t * time.Second) // 模拟耗时的任务
			log.Printf("Done")
			d.Ack(true) // 手动传递消息确认  这里false和true好像都可以
		}
	}()
	log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
	<-forver
}
func main() {
	demo1()
}
